/**
 * 服务端类：socket服务端，接收客户端发来的请求，统计请求次数，把接受到的
 * 信息逆序然后发给对应的客户端。
 *
 * 2008-3-17
 * @author 李威
 *
 *
 */
package lsd.server;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class ServerService implements Server, Runnable {

    private static int count = 0;

    private Socket     socket;

    public ServerService(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        init();
    }

    /**
     * 初始化服务端socket，接收客户端发来的请求，把接收到的信息逆序然后发给对应的客户端
     */
    public void init() {
        //初始化服务端socket，接收客户端发来的请求，把接收到的信息逆序然后发给对应的客户端
        System.out.println("A new connection start~!");
        try {
            //读

            StringBuffer sb = new StringBuffer();
            InputStream reader = socket.getInputStream();
            OutputStream send = socket.getOutputStream();
            while (true) {
                int n = 1024;
                byte[] buffer = new byte[n];
                int sum = reader.read(buffer);
                if (sum != -1)
                    sb.append(new String(buffer).substring(0, sum));

                send.write(inverseString(sb.toString()).getBytes());
                send.flush();
                sb.delete(0, sb.length());
                this.count++;
                if (sum == -1)
                    break;
            }
            reader.close();
            send.close();
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 把字符串逆序输出
     * 
     * @param s 需要转换的字符串
     * @return 逆序的字符串
     */
    public String inverseString(String s) {
        StringBuffer sb = new StringBuffer();
        char[] c = s.toCharArray();
        for (int i = s.length() - 1; i > -1; i--) {
            sb.append(c[i]);
        }
        return sb.toString();
    }

    public static int getCount() {
        return count;
    }
}
